from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse
from apps.areas.models import Area
from django.core.cache import cache


class AreaView(View):
    def get(self, request):
        # 先查询缓存数据
        province_list = cache.get('province')
        # 若没有缓存，则查询数据库
        if province_list is None:
            # 1.查询省份信息
            provinces = Area.objects.filter(parent=None)
            # 2.将查询数据转化为字典数据
            province_list = []
            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            # 保存缓存数据
            # cache.set('key', 内容, 有效期)
            cache.set('province', province_list, 24 * 3600)

        # 3.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class SubAreaView(View):

    def get(self, request, id):
        # 先获取缓存数据
        data_list = cache.get('city_%s' % id)
        if data_list is None:
            up_level = Area.objects.get(id=id)
            # 要用get而不是fitter，不然会报错'QuerySet' object has no attribute '<related_model_name>'
            down_level = up_level.subs.all()
            # down_level = Area.objects.filter(parent_id=id)
            data_list = []
            for item in down_level:
                data_list.append({
                    'id': item.id,
                    'name': item.name
                })
            # 缓存数据
            cache.set('city_%s' % id, data_list, 24 * 3600)

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': {'subs': data_list}})
